<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="../../plugins/element-ui/index.css"/>
    <link rel="stylesheet" href="../../styles/common.css"/>
    <link rel="stylesheet" href="../../styles/page.css"/>
    <style>
        .selectInput {
            position: relative;
            width: 100%;
            min-width: 100px;
        }

        .selectInput .flavorSelect {
            position: absolute;
            width: 100%;
            padding: 0 10px;
            border-radius: 3px;
            border: solid 1px #00FA9A;
            line-height: 30px;
            text-align: center;
            background: #fff;
            top: 50px;
            z-index: 99;
        }

        .selectInput .flavorSelect .items {
            cursor: pointer;
            display: inline-block;
            width: 100%;
            line-height: 35px;
            border-bottom: solid 1px #f4f4f4;
            color: #666;
        }

        .selectInput .flavorSelect .none {
            font-size: 14px;
        }

        #student-app .uploadImg .el-form-item__label::before {
            content: '*';
            color: #00FA9A;
            margin-right: 4px;
        }

    </style>
</head>
<body>
<div class="addBrand-container" id="member-student-app">
    <div class="container">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" :inline="true" label-width="180px"
                 class="demo-ruleForm">
            <h1>编辑会员信息</h1>
            <div>
                <el-form-item label="账号名:" prop="username">
                    <el-input v-model="ruleForm.username" placeholder="请填写老师账号名" maxlength="20"/>
                </el-form-item>
            </div>
            <div>
                <div>
                    <el-form-item label="头像:" prop="user.head" class="uploadImg">
                        <el-upload
                                class="avatar-uploader"
                                action="http://localhost:8080/common/upload"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess1"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl1" :src="imageUrl1" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </div>
            </div>
            <div>
                <div>
                    <el-form-item label="形象照:" prop="user.image" class="uploadImg">
                        <el-upload
                                class="avatar-uploader"
                                action="http://localhost:8080/common/upload"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess2"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl2" :src="imageUrl2" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </div>
            </div>

            <div>
                <el-form-item label="会员名字:" prop="name">
                    <el-input v-model="ruleForm.sysUser.name" placeholder="请填写会员名字" maxlength="20"/>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="昵称:" prop="nickname">
                    <el-input v-model="ruleForm.sysUser.nickname" placeholder="请填写会员昵称" maxlength="20"/>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="年龄:" prop="age">
                    <el-input v-model="ruleForm.sysUser.age" placeholder="请填写会员年龄" maxlength="20"/>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="性别:" prop="gender">
                    <el-radio-group v-model="ruleForm.sysUser.gender">
                        <el-radio label="男">男</el-radio>
                        <el-radio label="女">女</el-radio>
                    </el-radio-group>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="生日:" prop="birthday">
                    <el-date-picker v-model="ruleForm.sysUser.birthday" type="date" placeholder="选择日期"
                                    @change="timeupdate()">
                    </el-date-picker>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="身份证号:" prop="idNumber">
                    <el-input v-model="ruleForm.sysUser.idNumber" placeholder="请填写身份证号" maxlength="20"/>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="电话:" prop="phone">
                    <el-input v-model="ruleForm.sysUser.phone" placeholder="请填写电话" maxlength="20"/>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="邮箱:" prop="email">
                    <el-input v-model="ruleForm.sysUser.email" placeholder="请填写所在邮箱" maxlength="20"/>
                </el-form-item>
            </div>

            <div>
                <el-form-item label="店铺名称:" prop="shopkeeperName">
                    <el-select v-model="ruleForm.shopkeeperName" placeholder="请选择">
                        <el-option v-for="item in shopkeepers" :key="item" :label="item"
                                   :value="item">{{item}}
                        </el-option>
                    </el-select>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="会员标签">
                    <el-select v-model="ruleForm.sysUser.tag" multiple placeholder="请选择标签">
                        <el-option
                                v-for="tag in tagOptions"
                                :key="tag"
                                :label="tag"
                                :value="tag">
                        </el-option>
                    </el-select>
                </el-form-item>
            </div>
            <div>
                <el-form-item label="等级:" prop="level">
                    <el-select v-model="ruleForm.level" placeholder="请选择">
                        <el-option
                                v-for="item in levelOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.label">
                        </el-option>
                    </el-select>
                </el-form-item>
            </div>
            <div class="subBox address">
                <el-form-item>
                    <el-button @click="goBack()">取消</el-button>
                    <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
                </el-form-item>
            </div>
            <h1 style="margin-top: 30px;">该会员所有会员卡</h1>
            <el-table :data="tableData1" stripe class="tableBox" max-height="500">
                <el-table-column prop="name" label="会员卡名称" align="center"></el-table-column>
                <el-table-column prop="type" label="会员卡类型" align="center"></el-table-column>
                <el-table-column prop="startTime" label="办卡时间" align="center"></el-table-column>
                <el-table-column prop="day" label="有效期(天)" align="center" width="125"></el-table-column>
                <el-table-column prop="remainingNumber" label="剩余次数(次)" align="center"
                                 width="125"></el-table-column>
                <el-table-column prop="remainingTime" label="剩余时间(天)" align="center"
                                 width="125"></el-table-column>
                <el-table-column prop="endTime" label="到期时间" align="center"></el-table-column>
                <el-table-column prop="status" label="会员卡状态" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.status=='生效中'?'success':'danger'">
                            {{row.status}}
                        </el-tag>
                    </template>
                </el-table-column>
            </el-table>
            <h1 style="margin-top: 30px;">为该会员选择会员卡</h1>
            <el-table :data="tableData2" stripe class="tableBox" max-height="500">
                <el-table-column prop="name" label="会员卡名称" align="center"></el-table-column>
                <el-table-column prop="background" label="图片" align="center">
                    <template slot-scope="{ row }">
                        <el-image style="width: auto; height: 40px; border:none;cursor: pointer;"
                                  :src="getImage(row.background)"
                                  :preview-src-list="[ `/common/download?name=${row.background}` ]">
                            <div slot="error" class="image-slot">
                                <img src="../../images/noImg.png" style="width: auto; height: 40px; border:none;">
                            </div>
                        </el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="type" label="会员卡类型" align="center"></el-table-column>
                <el-table-column label="原价" align="center">
                    <template slot-scope="scope">
                        <span style="margin-right: 10px;">￥{{ scope.row.oldPrice }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="售价" align="center">
                    <template slot-scope="scope">
                        <span style="margin-right: 10px;">￥{{ scope.row.price }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="day" label="有效期(天)" align="center"></el-table-column>
                <el-table-column prop="tags" label="标签" align="center"></el-table-column>
                <el-table-column label="操作" width="160" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" class="blueBug"
                                   @click="saveCard(scope.row.cardId,scope.row.name)">选择此卡
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <h1 style="margin-top: 30px;">该会员全部课程</h1>
            <el-table :data="tableData3" stripe class="tableBox" @selection-change="handleSelectionChange"
                      max-height="500">
                <!--                <el-table-column type="selection" width="25"></el-table-column>-->
                <el-table-column prop="courseName" label="课程名称" align="center"></el-table-column>
                <el-table-column prop="tag" label="课程标签" align="center"></el-table-column>
                <el-table-column prop="difficulty" label="课程难度" align="center"></el-table-column>
                <el-table-column prop="room" label="教室" align="center"></el-table-column>
                <el-table-column label="状态" prop="status" align="center">
                    <template #default="{ row }">
                        <el-tag :type="(row.status=='已预约'||row.status=='已签到')?'success':(row.status=='已下课'?'warning':'danger')">
                            {{row.status}}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="duration" label="课程时长(分)" align="center"></el-table-column>
                <el-table-column prop="startTime" label="开始时间" align="center" width="140"></el-table-column>
                <el-table-column prop="endTime" label="结束时间" align="center" width="140"></el-table-column>
                <el-table-column prop="nowPerson" label="已报人数" align="center"></el-table-column>
                <el-table-column prop="maxPerson" label="上限人数" align="center"></el-table-column>
            </el-table>
        </el-form>
    </div>
</div>
<!-- 开发环境版本，包含了有帮助的命令行警告 -->
<script src="../../plugins/vue/vue.js"></script>
<!-- 引入组件库 -->
<script src="../../plugins/element-ui/index.js"></script>
<!-- 引入axios -->
<script src="../../plugins/axios/axios.min.js"></script>
<script src="../../js/request.js"></script>
<script src="../../js/validate.js"></script>
<script src="../../js/index.js"></script>
<script src="../../api/member.js"></script>
<script src="../../api/shop.js"></script>
<script src="../../js/common.js"></script>
<script src="../../api/shopkeeper.js"></script>
<script>
    new Vue({
        el: '#member-student-app',
        data() {
            return {
                shopkeepers: [],
                userId: 1,
                memberId: '',
                shopkeeperId: '',
                value1: '',
                imageUrl1: '',
                imageUrl2: '',
                tableData1: [],
                tableData2: [],
                tableData3: [],
                rules: {
                    // name: [
                    //     {required: true, message: '请填写名称', trigger: 'blur'}
                    // ],
                    // idNumber: [
                    //     {required: true, message: '请填写身份证号', trigger: 'blur'},
                    //     {validator: this.validateIdNumber, trigger: 'blur'}
                    // ],
                    // phone: [
                    //     {required: true, message: '请填写电话', trigger: 'blur'},
                    //     {validator: this.validatePhone, trigger: 'blur'}
                    // ],
                    // email: [
                    //     {required: true, message: '请填写邮箱', trigger: 'blur'},
                    //     {type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change']}
                    // ]
                },
                checkList: [],
                page: 1,
                pageSize: 10,
                counts: 0,
                levelOptions: [
                    {value: '1', label: 'vip'},
                    {value: '2', label: 'svip'},
                    {value: '3', label: 'ssvip'}
                ],
                ruleForm: {
                    'id': '',
                    'name': '',
                    'email': '',
                    'level': '',
                    "sysUser": {
                        'head': '',
                        'images': '',
                        "addr": "",
                        "age": "",
                        "birthday": "",
                        "email": "",
                        "gender": "",
                        "idNumber": "",
                        "name": "",
                        "phone": "",
                        "username": ""
                    }
                },
                mak: false,
                options: [{
                    value: '选项1',
                    label: 'vip'
                }, {
                    value: '选项2',
                    label: 'svip'
                }, {
                    value: '选项3',
                    label: 'ssvip'
                }],
                value: '',
                tagOptions: []
            }
        },
        mounted() {
        },
        created() {
            //和修改相关
            this.userId = requestUrlParam('userId');
            this.memberId = requestUrlParam('memberId');
            this.shopkeeperId = requestUrlParam('shopkeeperId');
            this.actionType = this.userId ? 'edit' : 'add';
            if (this.userId) {
                this.init()
            }
            //查看该会员已选的所有会员卡
            this.openCard()
            //查看该会员的可选会员卡
            this.selectCard()
            //查看该会员全部课程
            this.selectClasses()
            //根据标签类型获取标签名字
            getTagListByType("会员").then(
                res => {
                    this.tagOptions = res.data;
                }
            )
        },
        methods: {
            handleAvatarSuccess1(res, file) {
                console.log("handleAvatarSuccess1")
                console.log(res.data);
                this.ruleForm.sysUser.head = res.data
                console.log(file);
                this.imageUrl1 = URL.createObjectURL(file.raw);
            },
            handleAvatarSuccess2(res, file) {
                console.log("handleAvatarSuccess2")
                console.log(res.data);
                this.ruleForm.sysUser.images = res.data
                console.log(file);
                this.imageUrl2 = URL.createObjectURL(file.raw);
            },
            async init() {
                var _this = this
                getAllShopkeeperName().then(res => {
                    _this.shopkeepers = res.data
                    console.log(_this.shopkeepers)
                })
                queryMemberById(this.userId).then(res => {
                    console.log(res);
                    if (String(res.code) === '1') {
                        this.ruleForm = {...res.data};
                        this.ruleForm.sysUser.tag = (res.data.sysUser.tag ? res.data.sysUser.tag.split(',') : [])
                        this.ruleForm.status = res.data.status == '1'
                        this.imageUrl1 = this.baseUrl + "" + res.data.sysUser.head
                        this.imageUrl2 = this.baseUrl + "" + res.data.sysUser.images
                    } else {
                        this.$message.error(res.msg || '操作失败')
                    }
                    if (String(res.code) === '1') {
                        this.ruleForm = res.data;
                    } else {
                        this.$message.error(res.msg || '操作失败')
                    }
                })
            },
            timeupdate() {
                var t = dateFormat("yyyy-MM-dd", this.ruleForm.sysUser.birthday)
                console.log(t)
                this.ruleForm.sysUser.birthday = t
            },
            //查看该会员的所有会员卡
            openCard() {
                getByIdWithCards(this.userId).then(res => {//请求结果处理
                    if (String(res.code) === '1') {
                        //对res.data结果进行处理，对res.data进行遍历
                        res.data.map(card => {
                            //转换办卡时间格式
                            card.startTime = new Date(card.startTime).toLocaleString()
                            /*1.计算到期时间  具体到哪一天是到期时间  endTime
                            * 到期时间=办卡时间+会员卡有效期天数 */
                            var start = new Date(card.startTime);
                            var end = new Date(start.setDate(start.getDate() + card.day));
                            card.endTime = end.toLocaleString()
                            /*判断会员卡有没有过期，如果过期了，那么会员卡剩余时间为0天*/
                            var nowTime = new Date();
                            var endTime = new Date(card.endTime);
                            if (nowTime >= endTime) {
                                // 如果会员卡过期，设置剩余天数为0，剩余次数为0，并且显示状态为已过期
                                card.remainingTime = 0
                                if (card.type === '期限卡') {
                                    card.buyCard.remainingNumber = '/'
                                } else {
                                    card.remainingNumber = 0
                                }
                                card.status = '已过期'
                            } else {
                                /*2.计算剩余次数  remainingNumber  如果是次卡，则计算剩余次数，期限卡显示： /
                                 * 剩余次数=会员卡总次数-会员卡已经使用次数 */
                                if (card.type === '期限卡') {
                                    card.remainingNumber = '/'
                                } else {
                                    card.remainingNumber = card.day - card.num
                                }
                                /* 3.计算剩余时间，剩余多少天  remainingTime
                                 * 剩余时间=结束时间与开始时间之间差多少天 */
                                var day = Math.ceil(Math.abs(endTime.getTime() - nowTime.getTime()) / (1000 * 60 * 60 * 24));
                                card.remainingTime = day;
                                /*4.设置会员卡状态，如果未过期，则显示生效中 */
                                card.status = '生效中'
                            }
                        })
                        this.tableData1 = res.data
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            },
            // 查询全部未办理的card信息
            async selectCard() {
                const params = {
                    memberId: this.memberId ? this.memberId : undefined,
                    shopkeeperId: this.shopkeeperId ? this.shopkeeperId : undefined
                };
                await getCardsNotSelected(params).then(res => {
                    if (String(res.code) === '1') {
                        this.tableData2 = res.data
                    }
                }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                })
            },
            //为该会员选择会员卡
            saveCard(cardId, name) {
                var _this = this
                var params = {
                    cardId: cardId,
                    memberId: this.memberId
                }
                this.$confirm("是否给该会员办理" + name + "?").then(res => {
                    saveByIdWithCard(params).then(res => {
                        console.log(res.code)
                        if (String(res.code) === '1') {
                            _this.$message.success("成功为会员办理" + name + "！")
                            _this.openCard()
                            _this.selectCard()
                        } else {
                            _this.$message.error(res.msg)
                        }
                    })
                }).catch(err => {
                    _this.$message("取消选卡")
                })
            },
            //查看该会员的全部课程
            selectClasses() {
                getByIdWithClasses(this.memberId).then(res => {
                    console.log('API Response:', res);
                    if (String(res.code) === '1') {
                        this.tableData3 = res.data;
                    } else {
                        console.error('API Error:', res.msg);
                        this.$message.error(res.msg || '获取课程数据失败');
                        this.tableData = []; // 清空表格或显示默认数据
                    }
                }).catch(error => {
                    console.error('Request failed:', error);
                    this.$message.error('请求失败: ' + error.message);
                });
            },

            submitForm(formName, st) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        const params = {
                            ...this.ruleForm,
                            sex: this.ruleForm.sex === '女' ? '0' : '1',
                            ...this.ruleForm.sysUser.tag = this.ruleForm.sysUser.tag.toString()
                        };
                        params.status = this.ruleForm ? 1 : 0;
                        delete params.updateTime;

                        editMember(params).then(res => {
                            if (res.code === 1) {
                                this.$message({
                                    message: '会员修改成功！',
                                    type: 'success',
                                    duration: 1500,  // 设置显示时间1.5秒
                                    onClose: () => {
                                        window.parent.goBack();
                                    }
                                });
                            } else {
                                this.$message.error(res.msg || '操作失败');
                            }
                        }).catch(err => {
                            this.$message.error('请求出错了：' + err);
                        });
                    } else {
                        return false;
                    }
                });
            },
            onChange(file) {
                if (file) {
                    const suffix = file.name.split('.')[1];
                    const size = file.size / 1024 / 1024 < 2;
                    if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
                        this.$message.error('上传图片只支持 png、jpeg、jpg 格式！');
                        this.$refs.upload.clearFiles();
                        return false
                    }
                    if (!size) {
                        this.$message.error('上传文件大小不能超过 2MB!');
                        return false
                    }
                    return file
                }
            },
            goBack() {
                window.parent.menuHandle({
                    id: '5',
                    url: 'page/member/list.html',
                    name: '用户管理'
                }, false)
            },
            // 验证身份证号 (18位)
            validateIdNumber(rule, value, callback) {
                if (!value) {
                    callback(new Error('请填写身份证号'));
                } else if (!/^\d{17}[\dXx]$/.test(value)) {
                    callback(new Error('请输入18位有效身份证号'));
                } else {
                    callback();
                }
            },

            // 验证手机号 (11位)
            validatePhone(rule, value, callback) {
                if (!value) {
                    callback(new Error('请填写电话'));
                } else if (!/^1[3-9]\d{9}$/.test(value)) {
                    callback(new Error('请输入11位有效手机号码'));
                } else {
                    callback();
                }
            },
            // 验证电子邮件
            validateEmail(rule, value, callback) {
                if (!value) {
                    callback(new Error('请填写邮箱'));
                } else if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value)) {
                    callback(new Error('请输入有效的邮箱地址'));
                } else {
                    callback();
                }
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            getImage(image) {
                return `/common/download?name=${image}`
            },
            // 全部操作
            handleSelectionChange(val) {
                let checkArr = [];
                val.forEach((n) => {
                    checkArr.push(n.id)
                });
                this.checkList = checkArr
            },
            handleSizeChange(val) {
                this.pageSize = val;
                this.init()
            },
            handleCurrentChange(val) {
                this.page = val;
                this.init()
            },

        }
    })
</script>
</body>
</html>